<?php
// +----------------------------------------------------------------------
// | TOPThink [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://topthink.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$

class IndexAction extends Action{
	//初始化
	public $user;
	public function __construct(){
		$this->user = D('User');
	}
    public function index(){
        $this->display();
    }
    public function login(){
		//清除登录信息
		session('PRE_ORDER_CHINA_SESS',null);
		$ReturnUrl = $_REQUEST['ReturnUrl'];
		if($ReturnUrl){
			$ReturnUrl = $ReturnUrl;
		}
		else{
			$ReturnUrl = 'Index/userIndex/';
		}
		if($this->isPost()){
			$user_name = $this->_param('userName');
			$user_pass = $this->_param('password');
			$checkcode = $this->_param('loginCode');
			$RememberMe = $this->_param('RememberMe');
			//校验用户名和密码
			$user_info = D('member')->where("user_name='$user_name' or email='$user_name'")->find();
			do{
			if(!$user_info){
				$errorInfo = '邮箱、用户名或密码输入错误，请重新填写。';
				break;
			}
			//未激活
			if($user_info['status'] == '0'){
				$this->redirect('Index/regUnactivation',array('uid'=>$user_info['user_id']),0);
				exit;
			}
			//登录成功
			else{
				$session = array();
				$session['user_id'] = $user_info['user_id'];
				$session['email'] = $user_info['email'];
				$session['user_name'] = $user_info['user_name'];
				session('PRE_ORDER_CHINA_SESS',$session);
				$this->redirect($ReturnUrl,1,'登录成功');
				exit;
			}
			}while(0);
			$this->assign('errorInfo',$errorInfo);
		}
		$this->assign('ReturnUrl',$ReturnUrl);
		$this->display();
	}
	public function register(){
		if($this->isPost()){
			$table = D("member");
			$data = array();
			$data['user_name'] = $_POST['regNickName'];
			$data['user_pass'] = md5($_POST['regPassword']);
			$data['email'] = $_POST['regEmail'];
			$data['true_name'] = $_POST['regTrueName'];
			$data['adress'] = $_POST['regAddress'];
			$data['mobile'] = $_POST['regMobile'];
			$data['add_time'] = date('YmdHis');
			$data['last_time'] = date('YmdHis');
			$data['status'] = '0';
			$checkcode = md5(time().mt_rand(1,100));
			$data['checkcode'] = $checkcode;

			//判断是否重复
			$result = $table->where("user_name='".$data['user_name']."'")->find();
			if($result){
				$this->error("用户名已存在！");
			}

			$result = $table->where("email='".$data['email']."'")->find();
			if($result){
				$this->error("Email已存在！");
			}
			//这儿是测试用
			$user_id = 2;
			redirect(__URL__.'/regSendEmail/uid/'.$user_id,1,'添加成功');
			exit;
			$user_id = $table->add($data);
			if(!$user_id){
				$this->error("添加失败");
			}
			else{
				redirect(__URL__.'/regSendEmail/uid/'.$user_id);
			}
		}
		
		$this->display();
	}
	//激活邮件提示
	public function regSendEmail(){
		$uid = $_REQUEST['uid'];
		$tb = D("member");
		$user_info = $tb->find($uid);
		if(!$user_info){
			$this->error('用户不存在!');
		}
		if($user_info['status'] == '1'){
			redirect(__URL__.'/regComplete/uid/'.$user_info['user_id']);
		}
		$this->display();
	}
	//重发邮件（AJAX）
	public function regReSendActivationEmail(){
		$uid = $this->_param('uid');//用户号
		$email = $this->_param('email');//邮件

		if(!$uid){
			$this->error("用户不存在");
		}
		
		//查询用户信息
		$user_info = D('member')->where("user_id='$uid'")->field("user_id,email,status")->find();
		if(!$user_info){
			$this->error("用户不存在");
		}
		//如果已经被激活
		if($user_info['status'] != '0'){
			$this->error('approved');
		}
		//如果email没有传，则得到用户的EMAIL
		if($email == ''){
			$email = $user_info['email'];
		}
		if(!$email){
			$this->error("EMAIL不存在");
		}
		//例行检查email是否已被其它占用
		$count = D('member')->where("email='$email' and user_id<>'$uid'")->count();
		
		if($count){
			$this->error("EMAIL:[$email]已被占用");
		}
		//更新用户的EMAIL,随机码，
		$checkcode = md5(time().mt_rand(0,100));
		$data = array(
			'email'=>$email,	
			'checkcode'=>$checkcode,
			'last_time'=>date('YmdHis')
		);
		$result = D('member')->where("user_id='$uid'")->save($data);
		if($result === false){
			$this->error("系统正忙...");
		}
		
		$subject = 'hello '.$email;
		$body = 'welcome to my world,your check code is '.$checkcode;
		$result = think_send_mail($email,$email,$subject,$body);
		if($result != 1){
			$this->error($result);
		}
		else{
			$this->success('success');
		}
	}
	//激活邮件，包括激活成功，失败，以及通知
	public function regActivation(){
		$checkcode = $this->_param('code');
		$uid = $this->_param('uid');
		//如果有校验码就是要验证
		if($checkcode){
			$user_info = D('member')->where("checkcode='$checkcode'")->find();
			if(!$user_info){
				$tpl = 'regActivationError';
			}
			else{
				$uid = $user_info['user_id'];
				$email = $user_info['email'];
				//判断是否已被激活
				if($user_info['status'] != '0'){
					$tpl = 'regActivationError';
				}
				else{
				//更新用户状态
					$data = array(
						'last_time'=>date('YmdHis'),
						'status'=>1,
					);
					$result = D('member')->where("user_id='$uid'")->save($data);
					if(!$result){
						$tpl = 'regActivationError';
					}
					else{
						$tpl = 'regActivationSucc';
					}
				}
				$this->assign('uid',$uid);
				$this->assign('email',$email);
			}
			
		}
		//啥都没干，发邮件的提示
		elseif($uid){
			$tpl = 'regActivation';
			$user_info = D('member')->where("user_id='$uid'")->find();
			if(!$user_info){
				$this->error('用户不存在');
			}
			elseif($user_info['status'] == '1'){
				$tpl = 'regActivationSucc';
			}
			$this->assign('uid',$uid);
			$this->assign('email',$user_info['email']);
		}
		else{
			$this->error("非法参数");
		}
		$this->display($tpl);
	}
	
	//登录发现未激活
	public function regUnactivation(){
		$uid = $this->_param('uid');
		$user_info = D('member')->where("user_id='$uid'")->find();
		if(!$user_info){
			$this->error("用户不存在");
			exit;
		}
		if($user_info['status'] != '0'){
			$this->redirect('Index/regActivation',array('uid'=>$user_info['user_id']),0);
			exit;
		}
		$this->assign('email',$user_info['email']);
		$this->assign('uid',$user_info['uid']);
		$this->display();
	}
	//验证码
	public function verify() {
        $type	 =	 isset($_GET['type'])?$_GET['type']:'gif';
        import("ORG.Util.Image");
        Image::buildImageVerify(4,1,$type);
    }
	

	//------------------------会员登录/注册--------------------------
	//会员登录信息
	public function userLoginInfo(){
		//未登录
		$TMPL_PARSE_STRING = C('TMPL_PARSE_STRING');
		$user = D('User');
		$cartNum = $this->_getShoppingCartNum();
		if(!$user->isLogin()){
			$this->success(array(
				's'=>"您好！游客 请 <a href=\"".__URL__."/login/\">[登录]</a> 或 <a href=\"".__URL__."/register/\">[免费注册]</a>",
				"bc"=>0,
				"p"=>$cartNum
			));
		}
		//已登录
		else{
			$msgNum = $user->getUserMsgNum();
			$this->success(array(
				's'=>"您好！".$user->getUserName()."<a href=\"".__URL__."/login/\">[退出]</a>".
						($msgNum ?
						"&nbsp;&nbsp;<a href=\"".__URL__."/userMsgBox/\" target=\"_blank\"><img src=\"".$TMPL_PARSE_STRING['__HOMEIMG__']."/an2.gif\" style=\"margin-right:3px;\" />新短信<span style=\"color:#ffff00;\">(".$msgNum.")</span></a>"
						:""),	
				'p'=>$cartNum,	//购物车数量
			));
		}
	}

	//抓取商品信息
	public function getUrlItem(){
		$url = html_entity_decode($this->_param('url'));
		$items = D('GetItem')->getItems($url);
		$this->error(array(
			'ProductUrl'=>$url,	
			'ProductName'=>$items['ProductName'],	
			'Price'=>$items['Price'],
			'Thumbnail'=>$items['Thumbnail'],
		));
	}

	//添加到购物车
	public function addToShoppingCart(){
		$item = array();
		$item['ProductName'] = $this->_param('ProductName');//商品名
		$item['ProductUrl'] = $this->_param('ProductUrl');//商品地址
		$item['Thumbnail'] = $this->_param('Thumbnail');//商品略图
		$item['Price'] = $this->_param('Price')*1;//价格
		$item['BuyNum'] = $this->_param('BuyNum')*1;//数量
		$item['Freight'] = $this->_param('Freight')*1;//大陆邮费
		$item['Remark'] = $this->_param('Remark');//备注
		
		$shopping_cart = session('DAIGOUSHOPPINGCART');
		if(!$shopping_cart) $shopping_cart = array();
		$shopping_cart[md5($item['ProductUrl'])] = $item;
		session('DAIGOUSHOPPINGCART',$shopping_cart);
		$this->success(array(
			"Message"=>"Success",
			"Error"=>""	
		),'',-1);
	}
	//更新购物车数量
	public function updateShoppingcartNum(){
		$url = $this->_param('url');
		$BuyNum = $this->_param('num');
		$urlkey = md5(html_entity_decode($url));
		$shopping_cart = session('DAIGOUSHOPPINGCART');
		if(!$shopping_cart) $shopping_cart = array();
		$item = & $shopping_cart[$urlkey];
		if(!$item){
			$this->error($urlkey);
			return;
		}
		$item['BuyNum'] = $BuyNum;
		session('DAIGOUSHOPPINGCART',$shopping_cart);
		$this->success($BuyNum*$item['Price']);
	}
	//更新购物车备注
	public function addShoppingCartRemark(){
		$url = $this->_param('url');
		$remark = $this->_param('remark');
		$urlkey = md5(html_entity_decode($url));
		$shopping_cart = session('DAIGOUSHOPPINGCART');
		if(!$shopping_cart) $shopping_cart = array();
		$item = & $shopping_cart[$urlkey];
		if(!$item){
			$this->error('Error');
			return;
		}
		$item['Remark'] = $remark;
		session('DAIGOUSHOPPINGCART',$shopping_cart);
		$this->success('Success');
	}
	public function deleteShoppingCartProducts(){
		$url = $this->_param('url');
		$url_arr = explode(',',$url);
		$shopping_cart = session('DAIGOUSHOPPINGCART');
		if(!$shopping_cart) $shopping_cart = array();
		foreach($url_arr as $url){
			$urlkey = md5(html_entity_decode($url));
			unset($shopping_cart[$urlkey]);
		}
		session('DAIGOUSHOPPINGCART',$shopping_cart);
		$jsdata = $this->_getShoppingCartJson($shopping_cart);
		$this->success($jsdata);
	}
	//购物车显示
	public function shoppingCart(){
		//如果是提交
		if($this->isPost()){
			$products = $this->_param('products');
			//记录被提交的产品
			session('DaiGouShoppingProductsPay',$products);
			//判断是否已登录
			$user = D('User');
			if(!$user->isLogin()){
				$this->redirect('/Index/login/&ReturnUrl='.urlencode('/Index/payConfirm/'));
			}
			else{
				$this->redirect('/Index/payConfirm/');
			}
			exit;
		}
		$returnUrl = urlencode(__INFO__);
		$shopping_cart = session('DAIGOUSHOPPINGCART');
		$user = D('User');
		$this->assign('userIsLogin',$user->isLogin());
		$this->assign('user',$user);
		$this->assign('userName',$user->getUserName());
		$this->assign('productNum',count($shopping_cart));
		$this->assign('returnUrl',$returnUrl);
		$this->display();
	}

	//确认订单
	public function payConfirm(){
		$returnUrl = urlencode(__INFO__);
		//校验是否登录
		$this->_checkLogin($returnUrl);
		$shopping_cart = session('DAIGOUSHOPPINGCART');
		$shopping_cart  = $shopping_cart ? $shopping_cart:array();

		//计算购物车信息
		$countFreight = 0;
		$countPrice = 0;
		$productsPay = (array)session('DaiGouShoppingProductsPay');
		foreach($shopping_cart as $k=>&$v){
			if(!in_array(htmlentities($v['ProductUrl']),$productsPay)) {
				unset($shopping_cart[$k]);
				continue;
			};
			$v['CountItemPrice'] = $v['BuyNum']*$v['Price'];
			$countFreight += $v['Freight'];
			$countPrice += $v['CountItemPrice'];
		}unset($v);
		$countAllPrice = $countFreight+$countPrice;
		$user = D('User');


		//如果是提交
		if($this->isPost()){
			$productsPay = $this->_param('tobuy');
			//计算购物车信息
			$countFreight = 0;
			$countPrice = 0;
			foreach($shopping_cart as $k=>&$v){
				if(!in_array($v['ProductUrl'],$productsPay)) {
					unset($shopping_cart[$k]);
					continue;
				};
				$v['CountItemPrice'] = $v['BuyNum']*$v['Price'];
				$countFreight += $v['Freight'];
				$countPrice += $v['CountItemPrice'];
			}unset($v);
			if(count($shopping_cart)==0){
				$this->error('购物车中无商品');
				exit;
			}
			$countAllPrice = $countFreight+$countPrice;//总价
			//生成订单
			$tbOrderInfo = D('orderInfo');
			//开始事务
			$tbOrderInfo->startTrans();
			//订单号
			$order_number = date('YmdHis').sprintf('%04s',mt_rand(1,9999));
			$exchange_rate = $this->_getSysConfig('Exchange_rate');
			$data = array(
				'order_id' => '',
				'order_number' => $order_number,
				'user_id' => $this->user->getUserId(),
				'amount' => $countAllPrice,
				'amount_thb' => $countAllPrice*$exchange_rate,
				'exchange_rate' => $exchange_rate,
				'amount_check' => $countAllPrice,
				'amount_thb_check' => $countAllPrice*$exchange_rate,
				'address' => $this->_param('order_user_address'),
				'rece_name' => $this->_param('order_user_name'),
				'mobile' => $this->_param('order_user_mobile'),
				'add_time' => date('YmdHis'),
				'order_status' => 0,
			);
			$order_id = $tbOrderInfo->add($data);
			if($order_id === false){
				$tbOrderInfo->rollback();
				$this->error('添加订单错误');
				exit;
			}
			$tbGoodsInfo = D('GoodsInfo');
			//添加到订单商品关系表
			foreach($shopping_cart as $v){
				$v['PriceThb'] = $v['Price']*$exchange_rate;
				$data = array(
					'goods_id'=>'',
					'order_id'=>$order_id,	
					'order_number'=>$order_number,
					'goods_src'=>$v['ProductUrl'],
					'goods_name'=>$v['ProductName'],
					'price_cny'=>$v['Price'],
					'price_thb'=>$v['PriceThb'],
					'num'=>$v['BuyNum'],
					'price_cny_check'=>0,
					'numprice_thb_check'=>0,
					'num_check'=>0,
					'is_brand'=>1,
					'goods_memo'=>$v['Remark'],
				);
				$goods_id = $tbGoodsInfo->add($data);
				if($goods_id === false){
					$tbOrderInfo->rollback();
					$this->error('添加订单商品错误','',1000);
					exit;
				}
			}
			//清空购物车
			//session('DAIGOUSHOPPINGCART',null);
			$tbOrderInfo->commit();
			$this->success('订单添加成功');
			exit;
		}

		$this->assign('userIsLogin',$user->isLogin());
		$this->assign('userName',$user->getUserName());
		$this->assign('returnUrl',$returnUrl);
		$this->assign('shoppingCartList',$shopping_cart);
		$this->assign('countFreight',$countFreight);
		$this->assign('countPrice',$countPrice);
		$this->assign('countAllPrice',$countAllPrice);

		$this->display();
	}

	//------------登录后的会员中心页面
	//会员中心首页
	//会员首页
	public function userIndex(){
		$this->_checkLogin(__ACTION__);
		$user = $this->user;
		$this->assign('user',$user);
		$this->display();
	}
	//得到数量(ajax)
	public function getMyMessCount(){
		$user = $this->user;
		$num = D('message')->where("rece_user='".$user->getUserId()."'")->count();
		$this->success(array(
				'TotalOrders'=>1,
				'UndoOrders'=>2,
				'FinishedOrders'=>3,
				'UnreadMsg'=>$user->getUserMsgNum()
			));
	}

	//我要代购
	public function userFillShoppingForm(){
		$this->assign('menuKey',ACTION_NAME);
		$this->display();
	}

	//查看订单列表
	public function userOrder(){
		$status = $this->_param('status');
		$sql = "select 
			a.*,
			b.order_status,
			b.exchange_rate,
			b.add_time
			from goods_info a 
			left join order_info b on b.order_id=a.order_id
			where b.user_id='".$this->user->getUserID()."'
		";
		$goods_list = D()->query($sql);
		$order_list = array();
		foreach($goods_list as $v){
			$order_list[$v['order_id']][] = $v;
		}
		$this->assign('menuKey',ACTION_NAME."_".$status);
		$this->assign('orderList',$order_list);
		$this->display();
	}

	//查看订单付款信息
	public function userPayList(){
		$status = $this->_param('status',null,0);
		$sql = "select 
			a.*
			from order_pay a 
			where a.user_id='".$this->user->getUserID()."'
			and status='".$status."'
		";
		$payList = D()->query($sql);
		$this->assign('menuKey',ACTION_NAME);
		$this->assign('status',$status);
		$this->assign('payList',$payList);
		$this->display();
	}
	//汇款记录提交
	public function userPayAdd(){
		$user = $this->user;
		if($this->isPost()){
			$orderNumber = $this->_param('orderNumber');
			$payTime = date('YmdHis',strtotime($this->_param('payDate').' 23:59:59'));
			$order_info = D("orderInfo")->where("order_number='".$orderNumber."' and user_id='".$user->getUserID()."'")->find();
			if(!$order_info){
				$this->error("订单不存在");	
			}
			$data = array(
				'order_id'=>$order_info['order_id'],
				'order_number'=>$order_info['order_number'],
				'amount'=>$this->_param('amount'),
				'pay_time'=>$payTime,
				'add_time'=>date('YmdHis'),
				'bank'=>$this->_param('bank'),
				'user_id'=>$user->getUserID(),
				'status'=>0,
				'oper_user'=>null,
			);
			$tb = D('orderPay');
			$result = $tb->add($data);
			if($result === false){
				$this->error('添加付款记录失败');
			}
			else{
				$this->success('添加付款记录成功');
			}
			exit;
		}
		$bankList = array(
			'泰国商业银行',
			'泰国银行',
			'曼谷银行',
		);
		$this->assign('menuKey',ACTION_NAME);
		$this->assign('bankList',$bankList);
		$this->display();
	}
	//以下是内部函数
	//返回购物车数据
	private function _getShoppingCartJson($shopping_cart){
		//返回信息
		$jsdata = array();
		foreach($shopping_cart as $v){
			$jsdata[] = array(
				"BuyNum"=>$v['BuyNum'],
				"Href"=>$v['ProductUrl'],
				"Thumbnail"=>$v['Thumbnail'],
				"Picture"=>$v['Thumbnail'],
				"Name"=>$v['ProductName'],
				"Price"=>$v['Price'],
				"PromotionPrice"=>$v['Price'],
				"Freight"=>$v['Freight'],
				"Remark"=>$v['Remark'],
				"Shop"=>array("Href"=>$v['ProductUrl'],"Name"=>"未知")
			);
		}
		return $jsdata;
	}

	//返回购物车数量
	private function _getShoppingCartNum(){
		//返回信息
		$shopping_cart = session('DAIGOUSHOPPINGCART');
		if(!$shopping_cart) $shopping_cart = array();
		return count($shopping_cart);
	}

	//校验是否登录，并且跳转到登录页
	private function _checkLogin($url=null){
		$user = D('User');
		if(!$user->isLogin()){
			$this->redirect('Index/login',array('ReturnUrl'=>urlencode($url)),0);
		}
		return true;
	}

	//配置系统信息
	private function _getSysConfig($key){
		static $__sys_config = array();
		if(!$__sys_config){
			$__sys_config = D('SysConfig')->select();
			$__sys_config = array_valtokey($__sys_config,"cfg_key","cfg_value");
		}
		return isset($__sys_config[$key]) ? $__sys_config[$key] : ''; 
	}
	
}